﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AvatarHelper;
using Avatar.Model;
using AvatarMembership.Model;
using System.Web.Security;
using Avatar.Common;
using Avatar.Company;

[Serializable]
public class CompanyUser
{
    string _user;
    public string User
    {
        get
        {
            return _user;
        }
        set
        {
            _user = value;
        }
    }

    string _companyName;
    public string CompanyName
    {
        get
        {
            return _companyName;
        }
        set
        {
            _companyName = value;
        }
    }
    int _serviceID;
    public int ServiceID
    {
        get
        {
            return _serviceID;
        }
        set
        {
            _serviceID = value;
        }
    }
    DateTime _registerTime;
    public DateTime RegisterTime
    {
        get
        {
            return _registerTime;
        }
        set
        {
            _registerTime = value;
        }
    }
}
public partial class Management_CompanyInfo : System.Web.UI.Page
{
    List<CompanyUser> _companys = new List<CompanyUser>();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            panel_Date.Visible = false;

            var _user = Roles.GetUsersInRole("企业用户");
            foreach (var _u in _user)
            {
                var _company = new CompanyUser();
                _company.User = _u;
                _company.CompanyName = CompanyInformationManager.GetCompanyInformation(_u) == null ? "未填写" : CompanyInformationManager.GetCompanyInformation(_u).CompanyName;
                _company.ServiceID = CompanyServiceManager.GetServiceType(_u) == null ? 1 : CompanyServiceManager.GetServiceType(_u).ServiceTypeID;
                _company.RegisterTime = Membership.GetUser(_u).CreationDate;
                _companys.Add(_company);
            }
            if (ViewState["company"] == null)
            {
                ViewState.Add("company", _companys);
            }
            else
            {
                ViewState["company"] = _companys;
            }

            ddl_ServiceType.DataBind();
            this.gvBind(0);
        }
        try
        {
            _companys = (List<CompanyUser>)ViewState["company"];
        }
        catch
        {
            Response.Redirect("./companyinfo.aspx");
        }
    }
    protected void btn_Vip_Click(object sender, EventArgs e)
    {
        Button _btn = sender as Button;
        var _company = _btn.CommandArgument;
        using (var _adc = DBHelper.GetDataContext())
        {
            var _companyService = _adc.CompanyService.FirstOrDefault(s => s.Company == _company);
            if (_companyService != null)
            {
                _companyService.ServiceTypeID = 2;
            }
            else
            {
                _companyService = new CompanyService();
                _companyService.ServiceTypeID = 2;
                _companyService.Company = _company;

                _adc.CompanyService.InsertOnSubmit(_companyService);
            }
            _adc.SubmitChanges();
        }
        var _co = _companys.FirstOrDefault(c => c.User == _company);
        if (_co != null) _co.ServiceID = 2;

        this.gvBind(0);
    }
    protected void btn_Monthly_Click(object sender, EventArgs e)
    {
        Button _btn = sender as Button;
        var _company = _btn.CommandArgument;
        using (var _adc = DBHelper.GetDataContext())
        {
            var _companyService = _adc.CompanyService.FirstOrDefault(s => s.Company == _company);
            if (_companyService != null)
            {
                _companyService.ServiceTypeID = 3;
            }
            else
            {
                _companyService = new CompanyService();
                _companyService.ServiceTypeID = 3;
                _companyService.Company = _company;

                _adc.CompanyService.InsertOnSubmit(_companyService);
            }
            _adc.SubmitChanges();
        }
        var _co = _companys.FirstOrDefault(c => c.User == _company);
        if (_co != null) _co.ServiceID = 3;

        this.gvBind(0);
        Helper.ShowMassage("设定包月用户成功，请转到 包月用户 管理界面为该用户设定到期日期。");
    }
    protected void btn_Up_Click(object sender, EventArgs e)
    {
        var _page = Convert.ToInt32(lbl_Current.Text)-1;
        if (_page > 0) _page -= 1;
        this.gvBind(_page);
    }
    protected void btn_Down_Click(object sender, EventArgs e)
    {
        var _page = Convert.ToInt32(lbl_Current.Text)-1;
        if (_page < Convert.ToInt32(lbl_Total.Text)-1) _page += 1;
        this.gvBind(_page);
    }
    protected void btn_Goto_Click(object sender, EventArgs e)
    {
        int _page = 0;
        try
        {
            if (!string.IsNullOrEmpty(txt_PageNumber.Text)) _page = Convert.ToInt32(txt_PageNumber.Text) - 1;
        }
        catch { }
        this.gvBind(_page);
    }
    protected void gvBind(int _page)
    {
        string _key = txt_KeyWord.Text;
        int _take = 15;
        lbl_Current.Text = (_page + 1).ToString();

        if (string.IsNullOrEmpty(_key))
        {
            lbl_Total.Text = (_companys.Count(c => c.ServiceID == Convert.ToInt32(ddl_ServiceType.SelectedValue)) / _take).ToString();
            if (lbl_Total.Text == "0") lbl_Total.Text = "1";
            ListView1.DataSource = _companys.Where(c => c.ServiceID == Convert.ToInt32(ddl_ServiceType.SelectedValue)).OrderByDescending(f => f.RegisterTime).Skip(_take * _page).Take(_take);
        }
        else
        {
            lbl_Total.Text = (_companys.Where(c => c.ServiceID == Convert.ToInt32(ddl_ServiceType.SelectedValue) && (c.User.Contains(_key) || c.CompanyName.Contains(_key))).Count() / _take).ToString();
            if (lbl_Total.Text == "0") lbl_Total.Text = "1";
            ListView1.DataSource = _companys.Where(c => c.ServiceID == Convert.ToInt32(ddl_ServiceType.SelectedValue) && (c.User.Contains(_key) || c.CompanyName.Contains(_key))).OrderByDescending(f => f.RegisterTime).Skip(_take * _page).Take(_take);
        } ListView1.DataBind();
    }
    protected void btn_ExpirationDate_Click(object sender, EventArgs e)
    {
        panel_Date.Visible = true;
        var _btn = sender as Button;
        txt_Company.Value = _btn.CommandArgument;
    }
    protected void btn_Set_Click(object sender, EventArgs e)
    {
        try
        {
            DateTime _date = DateTime.MinValue;
            try
            {
                _date = Convert.ToDateTime(txt_ExDate.Text);
            }
            catch (Exception)
            {
                throw new Exception("日期输入格式错误，请重新输入。");
            }
            if (_date <= DateTime.Today) throw new Exception("日期必须大于今日。");

            var _company = txt_Company.Value;
            using (var _adc = DBHelper.GetDataContext())
            {
                var _exDate = _adc.CompanyMonthlyUserExpirationDate.FirstOrDefault(d => d.Company == _company);
                if (_exDate != null)
                {
                    _exDate.ExpirationDate = _date;
                }
                else
                {
                    _exDate = new CompanyMonthlyUserExpirationDate();
                    _exDate.Company = _company;
                    _exDate.ExpirationDate = _date;

                    _adc.CompanyMonthlyUserExpirationDate.InsertOnSubmit(_exDate);
                }
                _adc.SubmitChanges();
            }
            this.gvBind(0);
            panel_Date.Visible = false;
        }
        catch (Exception _e)
        {
            lbl_Error.Text = "错误:" + _e.Message;
        }
    }
    protected void btn_Edit_Click(object sender, EventArgs e)
    {
        Button _btn = sender as Button;
        var _id = _btn.CommandArgument;
        if (string.IsNullOrEmpty(_id))
        {

        }
    }
    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        Button _btn = sender as Button;
        var _user = _btn.CommandArgument;
        if (!string.IsNullOrEmpty(_user))
        {
            using (var _adc = DBHelper.GetDataContext())
            {
                var _info = _adc.CompanyInformation.FirstOrDefault(i => i.User == _user);
                if (_info != null)
                {
                    if (_info.InterViewRecord.Count > 0)
                    {
                        _adc.InterViewRecord.DeleteAllOnSubmit(_info.InterViewRecord);
                        _adc.SubmitChanges();
                    }
                    if (_info.Job.Count > 0)
                    {
                        foreach (var _j in _info.Job)
                        {
                            if (_j.InterViewRecord.Count > 0)
                            {
                                _adc.InterViewRecord.DeleteAllOnSubmit(_j.InterViewRecord);
                                _adc.SubmitChanges();
                            }
                            if (_j.JobApplicationRecord.Count > 0)
                            {
                                _adc.JobApplicationRecord.DeleteAllOnSubmit(_j.JobApplicationRecord);
                                _adc.SubmitChanges();
                            }
                            if (_j.JobFavorites.Count > 0)
                            {
                                _adc.JobFavorites.DeleteAllOnSubmit(_j.JobFavorites);
                                _adc.SubmitChanges();
                            }
                        }
                        _adc.Job.DeleteAllOnSubmit(_info.Job);
                        _adc.SubmitChanges();
                    }
                    if (_info.ResumeFavorites.Count > 0)
                    {
                        _adc.ResumeFavorites.DeleteAllOnSubmit(_info.ResumeFavorites);
                        _adc.SubmitChanges();
                    }
                    _adc.CompanyInformation.DeleteOnSubmit(_info);
                }
                var _contact = _adc.CompanyContact.FirstOrDefault(c => c.CompanyUserName == _user);
                if (_contact != null)
                {
                    _adc.CompanyContact.DeleteOnSubmit(_contact);
                    _adc.SubmitChanges();
                }
            }
            Membership.DeleteUser(_user);
            Response.Redirect(Request.Url.ToString());
        }
        else
        {
            lbl_Error.Text = "用户名不能为空";
        }
    }
    protected void btn_Search_Click(object sender, EventArgs e)
    {
        try
        {
            int _page = 0;
            var _keyWord = string.IsNullOrEmpty(txt_KeyWord.Text) ? string.Empty : txt_KeyWord.Text;

            this.gvBind(_page);
        }
        catch (Exception _e)
        {
            lbl_Error.Text = _e.Message;
        }
    }
    protected void btn_PasswordReset(object sender, EventArgs e)
    {
        try
        {
            Button _btn = sender as Button;
            var _userName = _btn.CommandArgument;
            if (string.IsNullOrEmpty(_userName)) throw new Exception("用户未找到");
            //=== 产生加密用的密码密钥 ===    
            string _salt = this.GenerateSalt();

            //=== 将明码密码加密(此时密码为"P@ssw0rd" 当然也可随机数生成) ===    
            string _password = this.EncryptToHashString("123456", _salt, "SHA1");

            using (var _adc = DBHelper.GetMembershipDataContext())
            {
                var _user = _adc.aspnet_Users.FirstOrDefault(u => u.UserName == _userName);
                if (_user != null)
                {
                    _user.aspnet_Membership.Password = _password;
                    _user.aspnet_Membership.PasswordSalt = _salt;

                    _adc.SubmitChanges();
                }
            }
            Helper.ShowMassage("密码已被初始化为:123456");
        }
        catch (Exception _e)
        {
            lbl_Error.Text = _e.Message;
        }
    }
    /// <summary>    
    /// 密码加密钥    
    /// </summary>    
    /// <returns></returns>    
    private string GenerateSalt()
    {
        byte[] data = new byte[0x10];
        new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(data);
        return Convert.ToBase64String(data);
    }
    /// <summary>    
    /// 哈希密码加密   
    /// </summary>    
    /// <param name="s">原始字符串</param>    
    /// <param name="saltKey">Salt加密字符串</param>    
    /// <param name="hashName">加密格式(MD5, SHA1, SHA256, SHA384, SHA512.)</param>    
    /// <returns>加密过的密码</returns>    
    private string EncryptToHashString(string s, string saltKey, string hashName)
    {
        byte[] src = System.Text.Encoding.Unicode.GetBytes(s);
        byte[] saltbuf = Convert.FromBase64String(saltKey);
        byte[] dst = new byte[saltbuf.Length + src.Length];
        byte[] inArray = null;
        System.Buffer.BlockCopy(saltbuf, 0, dst, 0, saltbuf.Length);
        System.Buffer.BlockCopy(src, 0, dst, saltbuf.Length, src.Length);
        System.Security.Cryptography.HashAlgorithm algorithm = System.Security.Cryptography.HashAlgorithm.Create(hashName);
        inArray = algorithm.ComputeHash(dst);
        return Convert.ToBase64String(inArray);
    }
}
